package com.itheima.dao.impl;

import com.itheima.dao.StudentDao;
import com.itheima.domain.Student;

import java.io.*;
import java.util.ArrayList;
/*
    持久化层实现类
 */
public class StudentDaoImpl implements StudentDao {
    @Override
    public Student add(String name, int age, int score) {
        //获取资源路径
        File file = new File("E:\\student.txt");
        //创建学生对象
        Student student = new Student();
        //将网页中传入的值存入学生对象
        student.setName(name);
        student.setAge(age);
        student.setScore(score);
        //创建字符缓冲输出流
        BufferedWriter bw = null;
        try {
            bw = new BufferedWriter(new FileWriter(file, true));
            //将学生对象的属性写入到文件中
            bw.write(student.getName() + "," + student.getAge() + "," + student.getScore());
            //换行
            bw.newLine();
            //刷新
            bw.flush();
        } catch (IOException e) {
            //异常处理
            e.printStackTrace();
        } finally {
            try {
                //关闭资源
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    public ArrayList<Student> search() {
        //创建学生对象集合用来存储从文件中读取到的学生信息
        ArrayList<Student> list = new ArrayList<>();
        //获取资源路径
        File file = new File("E:\\student.txt");
        //创建字符缓冲输入流
        BufferedReader br = null;
        try {
             br = new BufferedReader(new FileReader(file));
            String line;
            //循环存入集合中
            while ((line = br.readLine()) != null) {
                //创建学生对象
                Student student = new Student();
                //将读到的一行数据通过,进行切割
                String[] arr = line.split(",");
                //设置属性值
                student.setName(arr[0]);
                student.setAge(Integer.parseInt(arr[1]));
                student.setScore(Integer.parseInt(arr[2]));
                //将学生对象添加到集合中
                list.add(student);
            }
        } catch (FileNotFoundException e) {
            //异常处理
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(br!=null){
                try {
                    //关闭资源
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //将集合返回
        return list;
    }
}
